
$(document).ready(function () {
	//Color constants
        var suc_color = "#a5e921";  //On Success
        var alert_color = "red";    //On alert
        var user_added = false; //Refreshing on tab clicked all users
	// =========================================================
	// Tabs
	// =========================================================
	
	// Switching tabs in index.html
	// Reference: http://www.red-team-design.com/css3-jquery-folder-tabs
	
        if (gup('tab') == '2'){
            $("#tab_content div").hide(); // Initially hide all content
            $("#tabs li:last").attr("id","current");
            $("#documentation").fadeIn();
            $("#documentation").find(">:first-child").fadeIn();
            $("#documentation").find(">:first-child").show();
            $("#doc_buttons").fadeIn();
            $("#doc_buttons").show();
        }
        else if (gup('tab2') == 'manage_sprint'){
            $("#tab_content div").hide(); //Hide all content
            $("#tabs li:last").attr("id","current");
            $('#manage_sprints').fadeIn(); // Show content for current tab

            $("#manage_sprints div").show();
            $("#manage_sprints .project_editing").hide();
            $("#manage_sprints .project_deleting").hide();
            $("#manage_sprints .sprint_deleting").hide();
            $(".edit").removeClass("active");
            $(".delete").removeClass("active");
            
        }
        else if (gup('tab2') == 'add_project'){
             $("#tab_content div").hide(); //Hide all content
            $("#tabs li:last").prev("li").attr("id","current");
            $('#al_proj').fadeIn(); // Show content for current tab

            $("#al_proj div").show();
            $("#al_proj .project_editing").hide();
            $("#al_proj .project_deleting").hide();
            $("#al_proj .sprint_deleting").hide();
            $(".edit").removeClass("active");
            $(".delete").removeClass("active");
        }else{
            $("#tab_content div").hide(); // Initially hide all content
            $("#tabs li:first").attr("id","current"); // Activate first tab
            $("#tab_content div:first").fadeIn(); // Show first tab content
            $("#tab_content div:first div").show();
            $("#tab_content div:first .project_editing").hide();
            $("#tab_content div:first .project_deleting").hide();
        } 
        
        
        if (gup('imp_error') == '3'){
            alert("File doesn't exist.")
        }
        if (gup('imp_error') == '2'){
            alert("Wrong file format.")
        }
        if (gup('imp_error') == '1'){
            alert("File couldn't be read.")
        }

        $("#u_stories").click(function(e) {
            reloadWithoutParam(); 
        });
	$("#tabs a").click(function(e) {
	    e.preventDefault();
            $("#add_user > p").removeClass("alert_string").addClass("alert_string hidden"); //Izbrisemo sporocilo, da smo dodali userja
	    if ($(this).closest("li").attr("id") == "current") { //detection for current tab
	    	return;       
	    } else {             
		    $("#tab_content div").hide(); //Hide all content
		    $("#tabs li").attr("id",""); //Reset id's
		    $(this).parent().parent().attr("id","current"); // Activate this
		    $('#' + $(this).attr('name')).fadeIn(); // Show content for current tab
		    
		    $('#' + $(this).attr('name') + " div").show();
		    $('#' + $(this).attr('name') + " .project_editing").hide();
		    $('#' + $(this).attr('name') + " .project_deleting").hide();
		    $('#' + $(this).attr('name') + " .sprint_deleting").hide();
		    $(".edit").removeClass("active");
		    $(".delete").removeClass("active");
	    }
	    
	    // Always show input boxes
	    $(".input_box").show();
	});
        
	$(document).on("click",".refresh",function(){
            if(user_added){
                reloadWithoutParam();
                user_added=false;
            }
        });
	// =========================================================
	// Collapsible panels
	// =========================================================
	
	$(".edit").click(function (event) {
		$(".project_deleting").slideUp();
		$(".project_editing").not($(this).parent().parent().next(".project_editing")).slideUp();
		
		$(".edit").removeClass("active");
		$(".delete").removeClass("active");
		
		if (!$(this).parent().parent().next(".project_editing").is(":visible")) {
			$(this).addClass("active");
		}
		$(this).parent().parent().next(".project_editing").slideToggle("slow");
	});
	
	$(".delete").click(function (event) {
		$(".project_editing").slideUp();
		$(".project_deleting").not($(this).parent().parent().next().next(".project_deleting")).slideUp();
		
		$(".edit").removeClass("active");
		$(".delete").removeClass("active");
		
		if (!$(this).parent().parent().next().next(".project_deleting").is(":visible")) {
			$(this).addClass("active");
		}
		$(this).parent().parent().next().next(".project_deleting").slideToggle("slow");
	});
	
	
	// =========================================================
	// Dialogs
	// =========================================================

	var title = $("#title"),
    	content = $("#content"),
    	tests = $("#tests"),
    	value = $("#value"),
    	allFields = $([]).add(title).add(content).add(tests).add(value);
	    
	$(".edit_story").click(function (event) {
		event.preventDefault();
		
                $(".editing_story > p").removeClass("alert_string").addClass("alert_string hidden");
                $("#bval").removeClass("alert_string").addClass("alert_string hidden");
		title.val($(this).prev().prev().prev().prev().text());
                var breaks = new RegExp("<br>","g");
		content.val($(this).parent().next().html().replace(breaks, "\n"));		
		tests.val($(this).parent().next().next().html().replace(breaks, "\n"));
		
		$("#priority").find("option:selected").prop('selected', false);
		var priority_text = $(this).prev().prev().find(".priority").text();
		$("#priority option[value='"+priority_text+"']").prop('selected', true);
		
		value.val($(this).prev().prev().find(".value").text());
		
		$(this).attr('id', 'trigger_id');		
		$("#edit_dialog").dialog("open");
	});
	      
	$( "#edit_dialog" ).dialog({
            autoOpen: false,
	    height: 760,
	    width: 650,
	    modal: true,
	    buttons: {
	    	"Confirm": function(event) {
	         	// Vzemi stvari iz polj in jih zapisi spremenjene v bazo...
                                               
	         	var story_id = $("#trigger_id").parent().parent().find("input:hidden").val().replace(/ /g, '');         	
	         	var title = $('#title').val().replace(/ /g, '+');
                        //title = title.replace(/ /g, '+');
                        var breaks = new RegExp("\n","g");
	         	var content = $('#content').val().replace(/ /g, '+');
                        content = content.replace(breaks, "<br/>");
                        //content = content.replace(/ /g, '+');  
	         	var tests = $('#tests').val().replace(breaks, "<br/>");
                        tests = tests.replace(/ /g, '+');
                        //var tests = $('#tests').val();
	         	var priority = $("#priority").find("option:selected").val();
	         	var value = $('#value').val();
                        var usr_id_transfer = $('#usr_id_transfer').val();
                        
                        /*
                        if (isNaN(title) || title == null || title == ""){
                            $(".editing_story > p").removeClass("alert_string hidden").addClass("alert_string");                
                        }*/
                        
                        if (isNaN(value) || value < 1 || value > 10){
                            $("#bval").removeClass("alert_string hidden").addClass("alert_string").text("Value must be between 1 and 10!");
                        }else{
                            $("#bval").removeClass("alert_string").addClass("alert_string hidden").text("Value must be between 1 and 10!");
                        }
                        
                        var ajaxUrl = "php/editStory.php";
                        var ajaxData = "story_id="+story_id+"&title="+title+"&content="+content+"&tests="+tests+"&priority="+priority+"&value="+value+"&usr_id_transfer="+usr_id_transfer;
	         	ajaxData = ajaxData.replace(/ /g, '+');
                        var popUp = $(this); 
                        
                        var ajaxRequest = $.post(ajaxUrl,       //URL
                            ajaxData,                           //podatki
                            function(data) {                    //Funkcija ob uspehu
                                //alert("funData: "+ajaxData);  //DEBUG: izpis podatkov
                                var obj = $.parseJSON(data);
                                if(obj.success == 1){   //Ob uspe��nem sporo��ilu

                                    $(".editing_story > p").removeClass("alert_string").addClass("alert_string hidden");

                                    var priorString = "";
                                    if (priority == 1)
                                        priorString = "must have";
                                    else if (priority == 2)
                                        priorString = "should have";
                                    else if (priority == 3)
                                        priorString = "could have";
                                    else if (priority == 4)
                                        priorString = "won't have this time";

                                    $("#trigger_id").prev().prev().prev().prev().html(title.replace(/\+/g, " "));
                                    $("#trigger_id").parent().next().html(content.replace(/\+/g, " "));
                                    $("#trigger_id").parent().next().next().html(tests.replace(/\+/g, " "));
                                    $("#trigger_id").prev().prev().find(".priority").html(priorString);
                                    $("#trigger_id").prev().prev().find(".value").html(value);                    

                                    popUp.dialog("close");
                                } else if (obj.missing == 0) 
                                    $(".editing_story > p").removeClass("alert_string hidden").addClass("alert_string").text("Story title is missing!");
                                else if (obj.bool == 0)
                                    $(".editing_story > p").removeClass("alert_string hidden").addClass("alert_string").text("This story title already exists!");
                                else
                                    $(".editing_story > p").removeClass("alert_string").addClass("alert_string hidden"); 
                           });    
                           
	        },
	        Cancel: function() {
                    $(this).dialog("close");
	        }
	    },
	    close: function() {
	    	$("#trigger_id").attr('id', '');
	      	$(".edit").removeClass("active");
	        allFields.val("");
	    }
	});
	
	$(".delete_story").click(function (event) {
            event.preventDefault();
            $(this).attr('id', 'trigger_id');
            $("#delete_dialog").dialog("open");
	});
	
	$("#delete_dialog").dialog({
            autoOpen: false,
	    height: 200,
	    width: 650,
	    modal: true,
	    buttons: {
	    	"Delete": function() {
                    // Izbrisi zgodbo iz baze z AJAX klicem in nato odstrani iz HTML...
                    var story_id = $("#trigger_id").parent().parent().find("input:hidden").val()

                    var ajaxUrl = "php/deleteStory.php";
                    var ajaxData = "story_id="+story_id;
                    ajaxData = ajaxData.replace(/ /g, "");

                    var ajaxRequest = $.post(ajaxUrl,       //URL
                        ajaxData,                           //podatki
                        function(data) {                    //Funkcija ob uspehu
                            //alert("funData: "+ajaxData);  //DEBUG: izpis podatkov
                            var obj = $.parseJSON(data);
                            if(obj.success == 1){   //Ob uspe��nem sporo��ilu

                            }else{

                            }
                        });
                        
                                             
                    $("#trigger_id").parent().parent().remove();
	         	
	            $(this).dialog("close");
	        },
	        Cancel: function() {
	          	$(this).dialog("close");
	        }
	    },
	    close: function() {
	    	$("#trigger_id").attr('id', '');
	      	$(".edit").removeClass("active");
	        allFields.val("");
	    }
	});
        
        // SPRINT DELETE
        var sprint_delete;
	$('.delete_sprint').click(function (event) {
		event.preventDefault();
                sprint_delete = $(this);
		$("#delete_sprint_dialog").dialog("open");
	});
	$("#delete_sprint_dialog").dialog({
            autoOpen: false,
	    height: 200,
	    width: 650,
	    modal: true,
	    buttons: {
	    	"Delete": function() {
                    var sprint_id = sprint_delete.parent().parent().find('input:hidden').val();
                    $.get("./php/editSprint.php?delete=1&sprint_id="+sprint_id, function(data){
                        if(data == "1"){  // Remove from html if deleting in AJAX succesfull
                            sprint_delete.parent().parent().slideUp('slow');
                        }
                    });
	         	
	            $(this).dialog("close");
	        },
	        Cancel: function() {
	          	$(this).dialog("close");
	        }
	    },
	    close: function() {
	    	$("#trigger_id").attr('id', '');
	      	$(".edit").removeClass("active");
	        allFields.val("");
	    }
	});
        
	$(".notes_story").click(function (event) {
		
		event.preventDefault();
		$(this).attr('id', 'trigger_id');
		
        var story_id = $(this).parent().parent().find("input:hidden").val();
        // za debuggirane
        //$('#username').html(story_id);
        
        var ajaxUrl = "php/getStoryNotes.php";
        var ajaxData = "story_id="+story_id;
	    //ajaxData = ajaxData.replace(/ /g, '+');
        var popUp = $(this); 
                        
        var ajaxRequest = $.post(ajaxUrl,       //URL
        	ajaxData,                           //podatki
            function(data) {                    //Funkcija ob uspehu
            	//alert("funData: "+ajaxData);  //DEBUG: izpis podatkov
                var obj = $.parseJSON(data);
                notes = obj.story_notes;
                //alert(notes);
                $("#notes_dialog textarea").val(notes);
                                
    	});    
                        
		//$('#notes').val($(this).parent().parent().find(".comments").text());
		$("#notes_dialog").dialog("open");
		
		
	});
	
	$( "#notes_dialog" ).dialog({
		autoOpen: false,
	    height: 310,
	    width: 650,
	    modal: true,
	    buttons: {
	    	"Save": function() {
	         	// Shrani notes...
	         	var story_id = $("#trigger_id").parent().parent().find("input:hidden").val()
	         	var notes = $('#notes').val();
	         		         		
			         	//if (notes == "") {
			         	//	$("#trigger_id").parent().parent().find(".comment_separator").addClass("hidden");
			         	//	$("#trigger_id").parent().parent().find(".comments").addClass("hidden");
			         	//	$("#trigger_id").parent().parent().find(".comments").html("");
			         	//} else {
			         	//	$("#trigger_id").parent().parent().find(".comment_separator").removeClass("hidden");
			         	//	$("#trigger_id").parent().parent().find(".comments").removeClass("hidden");
			         	//	$("#trigger_id").parent().parent().find(".comments").html(notes);
			         	//}
                        
                        var ajaxUrl = "php/addStoryNotes.php";
                        var ajaxData = "story_id="+story_id+"&notes="+notes;
	         			ajaxData = ajaxData.replace(/ /g, '+');
                        var popUp = $(this); 
                        
                        var ajaxRequest = $.post(ajaxUrl,       //URL
                            ajaxData,                           //podatki
                            function(data) {                    //Funkcija ob uspehu
                                //alert("funData: "+ajaxData);  //DEBUG: izpis podatkov
                                //var obj = $.parseJSON(data);
                                //notes = obj.story_notes;
                                //alert(notes);
                                 
                           });              
                        	         	
	            $(this).dialog("close");
	        },
	        Cancel: function() {
	          	$(this).dialog("close");
	        }
	    },
	    close: function() {
	    	$("#trigger_id").attr('id', '');
	      	$(".edit").removeClass("active");
	        allFields.val("");
	    }
	});
        
        //++++++++  PLANNING POKER  +++++++++
	//Planning poker variables
	var pokerRefreshInterval;
        var activePoker=false;
        var story_id;
        var story_change;
        var activeRound = 0;
        var isScrumMaster = false;
        
	$(".poker_story").click(function (event) {
		//Pridobimo story id, za generiranje tabele
                story_id = $(this).parent().parent().find("input:hidden").val();
                var renderControls = true;  //Kdaj izrisujemo kontrole, za vnos ocene...
                //Preverimo, ��e je igra aktivna
                $.get("./php/activePoker.php?story_id="+story_id,function(data){
                    if(data > 0 ){
                        activePoker = true;
                        renderControls = true;
                    }
                    //Gumbu moramo spremeniti ime
                    if(activePoker && isScrumMaster){
                        $(".ui-dialog-buttonpane button:contains('New round') span").text("End round");
                    }
                });
                
                event.preventDefault();
                story_change=$(this);   //Zapolnimo si za kasneje
                
                //��e nismo scrum master v dialogu nimamo gumbov{
                if(!isScrumMaster){  
                    var options = {
                        buttons: {}
                    };
                    $( "#poker_dialog" ).dialog('option', options);
                }
                
                $("#poker_dialog").dialog("open");
                
                //Osve��ujemo v intervalih
                pokerRefreshInterval = setInterval(function(){
                    activeRound = $("#poker_dialog table tr:last td:first").text();
                    $.get("./php/poker_table.php?controls=estimate&story_id="+story_id+"&active_round="+activeRound, function(data){
                        podatki = $.parseJSON(data);
                        $("#poker_dialog #table").html(podatki.table);
                        if((podatki.controls == "" && $("#poker_dialog #controls").html()!="")||(podatki.controls != "" && $("#poker_dialog #controls").html()==""))
                            renderControls=true;
                        
                        if(renderControls){//} && podatki.poker_active >0){
                            //activePoker = true;
                            $("#poker_dialog #controls").html(podatki.controls);
                            renderControls = false;
                        }
                        else if(podatki.poker_active == 0){
                            $("#poker_dialog #controls").html("");
                            renderControls = true;
                        }
                    
                    });
                }, 80);
		
	});
        
        $.get("./php/getUserStatus.php",function(data){
            resp = $.parseJSON(data);
            if(resp.scrum_master == 1)
                isScrumMaster = true;
        });
	$( "#poker_dialog" ).dialog({
            autoOpen: false,
	    height: 800,
	    width: 650,
	    modal: true,
	    buttons: [
	    	{
	    		text: "New round",
	    		width: 200,
	    		click: function() {
                            story_id = $.trim(story_id);
                            if($(".ui-dialog-buttonpane button:contains('New round') span").text()=="New round"){
                                activeRound = $("#poker_dialog table tr:last td:first").text();
                                if(activeRound=="")
                                    activeRound = 1;
                                else activeRound++;
                                $.get("./php/activePoker.php?set="+activeRound+"&story_id="+story_id);
                                
                                $(".ui-dialog-buttonpane button:contains('New round') span").text("End round");
                            }
                            else{
                                $.get("./php/activePoker.php?set=0&story_id="+story_id);
                                $(".ui-dialog-buttonpane button:contains('End round') span").text("New round");
                                activePoker=false;
                            }
                            
	        	}
	        },
	        {
	        	text: "Use estimate",
	        	width: 200,
	        	click: function() {
                                var estimate = $( "#poker_dialog table tr:last td:last").text();
                            if(isNumber(estimate)){
                                //Zapis ocene v bazo
                                $.get("./php/useEstimate.php?estimate="+estimate+"&story_id="+story_id);
                                //Sprememba ocene na glavni strani
                                story_change.parent().find(".time_estimate").val(estimate+" pt");
                                $("#poker_dialog #controls .alert_string").remove();
                                $(this).dialog("close");
                            }
                            else{
                                $("#poker_dialog #controls .alert_string").remove();
                                $("#poker_dialog #controls").prepend("<p class=alert_string>You have to submit your estimate first.</p>")
                            }
	        	}
	        }
	    ],
	    close: function() {
	      	$(".edit").removeClass("active");
                $("#poker_dialog > .table").html("<img src='./dsg/loading.gif' alt='Loading...'>");
                $("#poker_dialog > .controls").html("");
                clearInterval(pokerRefreshInterval);    //Ustavimo interval osve��evanja polja
	        allFields.val("");
	    }
	});
	
	function isNumber(n) {
	  	return !isNaN(parseFloat(n)) && isFinite(n);
	}
	//Uporaba on, ker je live deprecated od 1.7
	$(document).on( "click" , "#poker_time_estimate_submit" , function(event) {
		event.preventDefault();
		var estimate = $("#poker_time_estimate").val();
                var current_round = $("#poker_dialog table tr:last td:first").text();
                $.trim(story_id);
                //alert(estimate+", "+ current_round + ", " +story_id);
                
                if(!isNumber(estimate) || estimate < 0){
                    $("#controls .alert_string").remove();
                    $("#poker_dialog #controls").prepend("<p class=alert_string>You must insert valid number, higher than 0.</p>")
                    //alert("You must insert valid number, higher than 0.");
                }
                else{ 
                    $.get("./php/submitEstimate.php?estimate="+estimate+"&current_round="+current_round+"&story_id="+story_id, function(data){
                        $("#controls .alert_string").remove();
                        $("#controls").html("");
                    });
                }
		/*$("#current_estimate").html(estimate);
		
		var sum = 0;
		$( ".current_round" ).each(function( index ) {
			if (isNumber(parseInt($(this).text(), 10))) {
				sum = sum + parseInt($(this).text(), 10);
			}
		});
		$("#current_average").html(sum);*/
	});
	
	// =========================================================
	// Brisanje projektov in uporabnikov
	// =========================================================
	
	$('.delete_project').click(function (event) {
		event.preventDefault();
		
		var project_id = $(this).parent().prev().prev().find('input:hidden').val();
		
		// AJAX call to delete from base with project_id
                var url = './php/deleteProject.php?id='+project_id;
		//$.get(url);
		
		
            // For later reference in AJAX call for remove
	    var $remove1 = $(this).parent().prev().prev();
	    var $remove2 = $(this).parent().prev();
	    var $remove3 = $(this).parent();
	    		
	    // Create an AJAX call to add a feed to database (http://www.w3schools.com/php/php_ajax_database.asp)
	    if (window.XMLHttpRequest)
	    	xmlhttp=new XMLHttpRequest();
	    else
	    	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	    	
	    xmlhttp.onreadystatechange=function() {
	    	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	    		// Odstrani
	    		$remove1.remove();
	    		$remove2.remove();
	    		$remove3.remove();
	    	}
	    }
	    xmlhttp.open("GET",url,true);
	    xmlhttp.send();
	    
	    // =========================================================
	    // !!!!!   PRIMER KAKO SE UPORABLJA TO Z AJAX KLICEM   !!!!!
	    // =========================================================
	    // ISTI PRINCIP ZA VSE TAKE STVARI
	    
//	    var project_id = $(this).parent().prev().prev().find('input:hidden').val();
//	    
	    // For later reference in AJAX call
//	    var $remove1 = $(this).parent().prev().prev().remove();
//	    var $remove2 = $(this).parent().prev().remove();
//	    var $remove3 = $(this).parent().remove();
//	    		
	    // Create an AJAX call to add a feed to database (http://www.w3schools.com/php/php_ajax_database.asp)
//	    if (window.XMLHttpRequest)
//	    	xmlhttp=new XMLHttpRequest();
//	    else
//	    	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
//	    	
//	    xmlhttp.onreadystatechange=function() {
//	    	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	    		// Odstrani
//	    		$remove1.remove();
//	    		$remove2.remove();
//	    		$remove3.remove();
//	    	}
//	    }
//	    xmlhttp.open("GET","SKRIPTA.php?PROJECT_ID="+project_id,true);
//	    xmlhttp.send();
	});
	
	$('.delete_user').click(function (event) {
		event.preventDefault();
		
		var user_id = $(this).parent().prev().prev().find('input:hidden').val();
		
		var $remove1 = $(this).parent().prev().prev().remove();
	    var $remove2 = $(this).parent().prev().remove();
	    var $remove3 = $(this).parent().remove();
		
            // AJAX call to delete from base with user_id
            $.get("./php/deleteUser.php?USER_ID="+user_id, function(data){
                $remove1.remove();
                $remove2.remove();
                $remove3.remove();
            });
		
	});
	
	// =========================================================
	// Editiranje projektov in uporabnikov
	// =========================================================
	
		$(".edit_user").click(function (event) {
		event.preventDefault();
		
		// Get all vars
		var user_id = $('input[name=user_id]', $(this).parent()).val();
		var username = $('input[name=username]', $(this).parent()).val();;
		var name = $('input[name=name]', $(this).parent()).val();
		var last_name = $('input[name=last_name]', $(this).parent()).val();
		var mail = $('input[name=mail]', $(this).parent()).val();
		var role = $(this).parent().find(".styled_select").find("select").find("option:selected").val();
		var pass = $('input[name=password]', $(this).parent()).val();
		var pass_confirm = $('input[name=password_confirm]', $(this).parent()).val();
		//var message = $(this).parent().parent().find(".alert_string").text();
		
		// $("#username").html(message);
		
		
		//Podatki iz forme
                var form = $('form.editing_form', $(this).parent().parent()).serialize();
                
                
                //AJAX request using jquery
                var ajaxReq = $.post("./php/editUser.php",               //URL
                                form,                         //podatki
                                function(data) {                  //Funkcija ob uspehu
                                    
                                    var obj = $.parseJSON(data);
                                    var id_msg = obj.id_msg;
                                    var username = obj.username;
                                    var mail = obj.mail;
                                    
                                    // alert(data);
                                    $("#error_msg").html(id_msg);
                                    
                                    if(obj.success == 1){
                                    	
                                    	$(this).parent().parent().prev().find('.left').html("<h4>"+username+"</h4>, "+mail);
                                    	$(".project_editing").slideUp();	
                                    	$("#username").html(username);
                                    	location.reload();
                                    }

                                })
		$(".edit").removeClass("active");
	
	});
	
	$(".edit_project").click(function (event) {
		event.preventDefault();
		// Get all vars
		var name = $('input[name=name]', $(this).parent()).val();
                var leader = $('select[name=leader] option:selected', $(this).parent()).text();
                
                //Podatki iz forme
                var form = $('form.editing_form', $(this).parent().parent()).serialize();
                
                
                //AJAX request using jquery
                var ajaxReq = $.post("./php/editProject.php",               //URL
                                form,                         //podatki
                                function(data) {                  //Funkcija ob uspehu
                                    //alert("funData: "+data);  //DEBUG: izpis podatkov
                                    var obj = $.parseJSON(data);
                                    if(obj.success == 1){   //Ob uspe��nem sporo��ilu
                                        $(".project_editing > p").removeClass("alert_string").addClass("alert_string hidden");
                                        
                                        // Dynamically edit page if AJAX succesfull
                                        //$(this) ne dela, ker smo v post metodi, gledamo spremenljivko event
                                        $(event.target).parent().parent().prev().find('.left').html("<h4>"+name+"</h4>, "+leader);
                                        $(".edit").removeClass("active");
                                        $(".project_editing").slideUp();
                                    }
                                    //Pri��lo je do napake na stre��niku, pri obdelavi podatkov
                                    else{
                                         $(".project_editing > p").removeClass("alert_string hidden").addClass("alert_string").text(obj.msg);
                                    }
                                })

	});
	//$("#add_project_submit").click(function (event) {
        $("#add_project_form").submit(function (event) {
		event.preventDefault();
                
                //Podatki iz forme
                var form = $('#add_project_form', $(this).parent().parent()).serialize();
                
                //AJAX request using jquery
                var ajaxReq = $.post("./php/addProject.php",               //URL
                                form,                         //podatki
                                function(data) {                  //Funkcija ob uspehu

                                                                       
                                    var obj = $.parseJSON(data);
                                    //alert(data);
                                    //alert("msg_data: "+obj.msg);
                                    $("#error_msg2").html(obj.msg);
                                    if(obj.success == 1){   //Ob uspe��nem sporo��ilu
                                       resetForm($('#add_project_form')); //Pobrisemo formo, ce je vse ok
                                       $("#error_msg2").css("color", suc_color);
                                       $("#error_msg2").hide();
                                       window.location = window.location.href.split("?")[0]+"?tab2=add_project"
                                    }
                                    else{
                                    // Pri��lo je do napake na stre��niku, pri obdelavi podatkov
                                         $("#error_msg2").css("color", alert_color);
                                    }
                                    
                                })
	});
	
	$("#add_sprint_submit").click(function (event) {
           event.preventDefault();
           
           $("#error_msg_sprint").html("");
           //Podatki iz forme
            var form = $('#add_sprint_form', $(this).parent().parent()).serialize();
            
            var ajaxReq =  $.post("./php/addSprint.php",               //URL
                                form,                                  //podatki
                                function(data) {                  //Funkcija ob uspehu
                                                                   
                                    var obj = $.parseJSON(data);
                                    
                                    //alert("msg_data: "+obj.msg);
                                    $("#error_msg_sprint").html(obj.msg);
                                    //alert(data);
                                    // NE DELA???
                                    if(obj.success == 1){   //Ob uspe��nem sporo��ilu
                                       resetForm($('#add_sprint_form')); //Pobrisemo formo, ce je vse ok
                                       
                                       window.location = window.location.href.split("?")[0]+"?tab2=manage_sprint";
                              		   //alert(data);
                                    }
                                   
                                    
                                })
        });
        
        $("#add_story_submit").click(function (event) {
            event.preventDefault(); 

            $(this).attr('id', 'trigger_button');
            //Podatki iz forme
            var form = $('#add_story_form', $(this).parent().parent()).serialize();

            //AJAX request using jquery
            var ajaxReq = $.post("./php/addStory.php",      //URL
                form,                                       //podatki
                function(data) {                            //Funkcija ob uspehu

                    var obj = $.parseJSON(data);
                    //alert("funData: "+form);              //DEBUG: izpis podatkov
                    if(obj.success == 1){                   //Ob uspe��nem sporo��ilu
                        $("#add_prior_zero").removeAttr("disabled");
                        resetForm($('#add_story_form'));    //Pobrisemo formo, ce je vse ok
                        $("#add_prior_zero").attr("disabled","disabled");
                        $("#story_exists").removeClass("alert_string").addClass("alert_string hidden");
                        $("#bval_new").removeClass("alert_string").addClass("alert_string hidden");
                        $("#add_story_success").removeClass("alert_string hidden").addClass("alert_string");//.text("Story has been added successfully!");  
                        $("#add_story_missing").removeClass("alert_string").addClass("alert_string hidden");
                    }else if(obj.bool > 0){
                        $("#add_story_success").removeClass("alert_string").addClass("alert_string hidden");                      
                        if (obj.bool == 1){
                            $("#story_exists").removeClass("alert_string").addClass("alert_string hidden");
                            $("#bval_new").removeClass("alert_string hidden").addClass("alert_string");//.text("Value must be between 1 and 10!");
                        }else if (obj.bool == 2){
                            $("#story_exists").removeClass("alert_string hidden").addClass("alert_string");//.text("This story title already exists!");
                            $("#bval_new").removeClass("alert_string").addClass("alert_string hidden");
                        }else if (obj.bool == 3){
                            $("#story_exists").removeClass("alert_string hidden").addClass("alert_string");//.text("This story title already exists!");
                            $("#bval_new").removeClass("alert_string hidden").addClass("alert_string");//.text("Value must be between 1 and 10!");
                        }
                        if (obj.ttl == 0){
                            //TLELE SE ZA VALUE!!!
                            $("#add_story_missing").removeClass("alert_string hidden").addClass("alert_string");//.text("Story title is missing!");
                            if (obj.aux == 0)
                                $("#bval_new").removeClass("alert_string").addClass("alert_string hidden");//.text("Value must be between 1 and 10!");
                            else
                                $("#bval_new").removeClass("alert_string hidden").addClass("alert_string");//.text("Value must be between 1 and 10!");
                        }
                        else{
                            $("#add_story_missing").removeClass("alert_string").addClass("alert_string hidden");
                            if (obj.aux == 0)
                                $("#bval_new").removeClass("alert_string").addClass("alert_string hidden");//.text("Value must be between 1 and 10!");
                            else
                                $("#bval_new").removeClass("alert_string hidden").addClass("alert_string");//.text("Value must be between 1 and 10!");
                        }
                    }                                   
                })
	});
	
        //Ni v uproabi
        //$("#add_user_submit").click(function (event) {
        $("#add_user_form").submit(function (event) {
		event.preventDefault();
                
                //Podatki iz forme
                var form = $('#add_user_form', $(this).parent().parent()).serialize();
                
                //AJAX request using jquery
                var ajaxReq = $.post("./php/addUser.php",               //URL
                                form,                         //podatki
                                function(data) {                  //Funkcija ob uspehu

                                    var obj = $.parseJSON(data);
                                    //alert("msg_data: "+obj.msg);
                                    
                                    if(obj.success == 1){   //Ob uspe��nem sporo��ilu
                                        resetForm($('#add_user_form')); //Pobrisemo formo, ce je vse ok
                                        $("#add_user > p").removeClass("alert_string hidden").addClass("alert_string").text(obj.msg).css( "color", suc_color );
                                        reloadWithoutParam();
                                        //user_added=true;
                                    }
                                    //Prislo je do napake na strezniku, pri obdelavi podatkov
                                    else{
                                         $("#add_user > p").removeClass("alert_string hidden").addClass("alert_string").text(obj.msg).css( "color", alert_color );
                                    }
                                })
		
	});
	$("#login_submit").click(function (event) {
		event.preventDefault();
                //Podatki iz forme
                var form = $('#login_form', $(this).parent().parent()).serialize();
                
                //alert(form);
                //AJAX request using jquery
                var ajaxReq = $.post("./php/loginUser.php",               //URL
                                form,                         //podatki
                                function(data) {                  //Funkcija ob uspehu
                                    //alert("funData: "+data);  //DEBUG: izpis podatkov
                                    var obj = $.parseJSON(data);
                                    if(obj.success == 1){   //Ob uspe��nem sporo��ilu samo redirectamo, kot bi obi��ajno
                                        $("#loginSection p").removeClass("alert_string").addClass("alert_string hidden");
                                        
                                        window.location = "control_panel.php";
                                    }
                                    //Pri��lo je do napake na stre��niku, pri obdelavi podatkov
                                    else{
                                        $("#loginSection p").removeClass("alert_string hidden").addClass("alert_string").text(obj.msg);
                                    }
                                })

	});
        
	$(".right_button").click(function (event) {
		$(".edit").removeClass("active");
		$(".delete").removeClass("active");
		$(".delete_sprint").removeClass("active");
		
		$(".project_deleting").slideUp();
		$(".project_editing").slideUp();
		$(".sprint_deleting").slideUp();
	});
	
	// =========================================================
	// Dodajanje zgodb v sprint
	// =========================================================
	
	
	$(".add_to_sprint_button").click(function (event) {
		event.preventDefault();
		
		var story_id = $(this).parent().parent().find('input:hidden').val();
		var sprint_id = $(this).parent().parent().find('input:hidden').next().val();
		
			
		if (window.XMLHttpRequest)
	    		xmlhttp=new XMLHttpRequest();
	    else
	    		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	    	
	    xmlhttp.onreadystatechange=function() {
	    		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		   		
					var response = xmlhttp.responseText;
					var obj = JSON.parse(response);
					
					if(obj.success == 0){
						alert(obj.msg);
						
					} else {
						location.reload();
					}
				}
	    	}
	    	xmlhttp.open("GET","./php/addStoryToSprint.php?story_id="+story_id+"&sprint_id="+sprint_id,true);
	    	xmlhttp.send();

	});
	
	
	// =========================================================
	// Editiranje time estimate sprint velocity
	// =========================================================
	$(".velocity").focusout(function (event) {
		var sprint_id = $(this).parent().parent().find("input:hidden").val();
                var velocity = $(this).val();
                var klik = $(this);
                if(isNumber(velocity) && velocity > 0){
                    klik.attr("disabled",true); //Just for feedback to user
                    $.get("./php/editSprint.php?sprint_id="+sprint_id+"&velocity="+velocity, function(data){
                        if(data == "1"){
                            setTimeout(function(){klik.attr("disabled",false)}, 100);   //End user feedback
                        }

                    });
                }
                else alert("Insert valid number higher than 0.")
		// Use AJAX to save new time estimate!
	});
	$(".delete_sprint").click(function (event) {
		$(".sprint_deleting").not($(this).parent().parent().next(".sprint_deleting")).slideUp();
		$(".delete_sprint").removeClass("active");
		
		if (!$(this).parent().parent().next(".sprint_deleting").is(":visible")) {
			$(this).addClass("active");
		}
		$(this).parent().parent().next(".sprint_deleting").slideToggle("slow");
	});
	
	
	$(".time_estimate").focusout(function (event) {
		
		var story_id = $(this).parent().parent().parent().find("input:hidden").val();
		var time = $(this).val();

		if(!isNaN(time) && (time > 0)){
			
			if (window.XMLHttpRequest)
	    		xmlhttp=new XMLHttpRequest();
	    	else
	    		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	    	
	    	xmlhttp.onreadystatechange=function() {
	    		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	    		// Odstrani
				var response = xmlhttp.responseText;
				var obj = JSON.parse(response);
				
				$(this).val(obj.story_time);
	    		}
	    	}
	    	xmlhttp.open("GET","./php/addTimeEstimate.php?story_id="+story_id+"&time="+time,true);
	    	xmlhttp.send();
			
			
		} else {
			$(this).val("");
		}
	
	    
	});
	
	$(".select_proj").click(function (event) {
		event.preventDefault();
                var proj_id = $(this).parent().prev().val();
                var usr_id = $("#usr_id_global").val();
                var form = "proj_id="+proj_id+"&usr_id="+usr_id;                

		$(".select_proj").removeClass("active");
		$(".select_proj").html("select");
		$(this).addClass("active");
		$(this).html("selected");
                
                var ajaxReq = $.post("./php/selectProject.php",     //URL
                                form,                               //podatki
                                function(data) {                    //Funkcija ob uspehu

                                    var obj = $.parseJSON(data);
                                    //alert("msg_data: "+obj.msg);
                                    
                                    if(obj.success == 1){           //Ob uspe��nem sporo��ilu                                  
                                        
                                    }
                                })
	});
        //Funkcija, ki resetira formo
        function resetForm($form) {
            $form.find('input:text, input:password, input:file, input[type=email], select, textarea').val('');
            $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
        }
        
     // =========================================================
    	// Tasks
    	// =========================================================
    	
    	$(document).on('click', '.accept_task', function (event) {
    		event.preventDefault();
    		
                var task_id = $(this).parent().parent().find("input[name=task_id]").val();
                var dev_id = $(this).parent().parent().find("input[name=developer]").val();
                
                var form = "task_id="+task_id+"&developer="+dev_id;
            
                var ajaxReq =  $.post("./php/editTask.php?method=accept",               //URL
                    form,                                  //podatki
                    function(data) {                  //Funkcija ob uspehu

                        var obj = $.parseJSON(data);

                        //alert("msg_data: "+obj.msg);
                        //$("#error_msg_sprint").html(obj.msg);
                        //alert(data);
                        if(obj.success == 1){   

                        }
                    });
    			
    		$(this).parent().next().html($("#username").html()+" (<a class=\"release_task\">release</a>)");
    		$(this).parent().html("Assigned");
                //$(this).parent().parent().html("<input type=\"hidden\" name=\"developer\" value=\""+dev_id+"\" />");
    	});
    	
    	$(document).on('click', '.release_task', function (event) {
    		event.preventDefault();
    		
                var task_id = $(this).parent().parent().find("input[name=task_id]").val();
                var dev_id = $(this).parent().parent().find("input[name=developer]").val();
                
                var form = "task_id="+task_id;
            
                var ajaxReq =  $.post("./php/editTask.php?method=release",               //URL
                    form,                                  //podatki
                    function(data) {                  //Funkcija ob uspehu

                        var obj = $.parseJSON(data);

                        //alert("msg_data: "+obj.msg);
                        //$("#error_msg_sprint").html(obj.msg);
                        //alert(data);
                        if(obj.success == 1){   

                        }
                    });
                
                //var prev = $(this).parent().parent().html();
                //$(this).parent().parent().html(prev + "<input type=\"hidden\" name=\"developer\" value=\""+dev_id+"\" />");    
    		$(this).parent().prev().html("<a class=\"accept_task\">Accept task</a>");
    		$(this).parent().html("Not selected");                

    	});
    	
    	$(".edit_tasks").click(function (event) {
    		event.preventDefault();
                var story_id = $(this).parent().prev().val();

                $.get("./php/editStoryTasks.php?story_id="+story_id,function(data){
                    $("#tasks_dialog").html(data);
                    $("#tasks_dialog").dialog("open");
                });
    		
    	});
    	updateTasks = false;
    	$( "#tasks_dialog" ).dialog({
    		autoOpen: false,
    		open: function(event, ui) {
    			$("input").blur();
                        
    		},
    	    height: 800,
    	    width: 650,
    	    modal: true,
    	    buttons: {
    	    	"Save": function() {
    	         	// Ne naredi nic, ker itak shranjujemo sproti
    	         	
    	            $(this).dialog("close");
    	        }
    	    },
    	    close: function() {
    	    	$("#trigger_id").attr('id', '');
    	        allFields.val("");
                updateTasks=false;
                location.reload();
    	    }
    	});
    	
    	$(document).on("click",".delete_task",function (event) {
    		event.preventDefault();
    		var task_id = $(this).parent().parent().find("input[type=hidden]").val();
    		$.get("./php/editStoryTasks.php?delete="+task_id);
    		// Delete task with name
    		
    		$(this).parent().parent().slideUp("slow");
    	});
    	$(document).on("focusout", ".task_name", function (event) {
                //Zato, ker focus out reagira že pri spreminjanju htmlja dinamično z JS
                if(updateTasks){
                    var newName = $(this).val();
                    var task_id = $(this).parent().parent().find("input[type=hidden]").val();
                    alert(newName + ", " + task_id);
                }
    		// Shrani new task name
    	});
    	
    	$(document).on("focusout", ".task_member", function (event) {
    		//Zato, ker focus out reagira že pri spreminjanju htmlja dinamično z JS
                var taskNameToSave = $(this).parent().parent().find(".task_name").val();
                var task_id = $(this).parent().parent().find("input[type=hidden]").val();
                var dev_id = $(this).val();
                if(dev_id > 0)
                    $.get("./php/editStoryTasks.php?task_id="+task_id+"&set_dev="+dev_id);

    		// Shrani member for task name
    	});
    	
    	$(document).on("focusout", ".task_estimate", function (event) {
    		//Zato, ker focus out reagira že pri spreminjanju htmlja dinamično z JS
                var task_id = $(this).parent().parent().find("input[type=hidden]").val();
                var estimate = $(this).val();
                //Če ni številka ali še ni vnešena je ne vnašamo v bazo...
                if(isNumber(estimate) && estimate > 0){
                    $.get("./php/editStoryTasks.php?task_id="+task_id+"&estimate="+estimate);
                }
                else if(estimate && estimate != "not set"){
                    alert("Insert valid number higher than 0.")

                }
    		// Shrani estimate for task name
    	});
    	
    	$(document).on("click", "#tasks_submit_new", function (event) {
    		event.preventDefault();
    		var taskNameToAdd = $("#tasks_input_description").val();
                var story_id = $("#story_id").val();
                if(taskNameToAdd.length > 0){
    		$.get("./php/editStoryTasks.php?task_title="+taskNameToAdd+"&storyid="+story_id, function(data){
                    //Refresh dialog
                    $.get("./php/editStoryTasks.php?story_id="+story_id,function(data){
                        $("#tasks_dialog").html(data);
                        $("#tasks_dialog").dialog("open");
                        
                    });
                });
                }
                else {
                    alert("Task name cannot be empty.")
                }
                
    		/*var tableRow = "<tr>\
>>>>>>> .r138
    			<td><input class=\"task_name\" type=\"text\" value=\""+taskNameToAdd+"\"/></td><td><a class=\"delete_task\">delete</a></td><td>\
    				<select class=\"task_member\">\
    					<option value=\"\" disabled selected>member</option>\
    					<option value=\"1\">gkolenc</option>\
    					<option value=\"2\">gurh</option>\
    					<option value=\"3\">akunovar</option>\
    				</select>\
    			</td><td><input class=\"task_estimate\" type=\"text\" name=\"time\"/></td>\
    		</tr>";
            
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                                    //DODAJAMO
                                    
                var form = "task_name="+taskNameToAdd+"&story_id="+story_id;//+project_id;
                alert(form);
            
                var ajaxReq =  $.post("./php/editTask.php?method=create",               //URL
                    form,                                  //podatki
                    function(data) {                  //Funkcija ob uspehu

                        var obj = $.parseJSON(data);

                        //alert("msg_data: "+obj.msg);
                        //$("#error_msg_sprint").html(obj.msg);
                        //alert(data);
                        if(obj.success == 1){   //Ob uspe��nem sporo��ilu
                           //resetForm($('#add_sprint_form')); //Pobrisemo formo, ce je vse ok
                               //alert(data);
                        }


                    });
                
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    		
                if (taskNameToAdd != ""){
                    $("#tasks_dialog_table").append(tableRow);
                    $("#tasks_input_description").val("");
                }
    		*/
    		// Add task with name to DB
    	});
    	
    	$('.confirm_story_submit').click(function (event) {
    		event.preventDefault();
    		
    		var storyId = $(this).parent().parent().find("input:hidden").val();
                
                //var form = $('#confirm_story_form', $(this).parent().parent()).serialize();
                var form = "story_id="+storyId;
            
                var ajaxReq =  $.post("./php/ownerEditStory.php?method=confirm",               //URL
                    form,                                  //podatki
                    function(data) {                  //Funkcija ob uspehu

                        var obj = $.parseJSON(data);

                        //alert("msg_data: "+obj.msg);
                        //$("#error_msg_sprint").html(obj.msg);
                        //alert(data);
                        if(obj.success == 1){   //Ob uspe��nem sporo��ilu
                           //resetForm($('#add_sprint_form')); //Pobrisemo formo, ce je vse ok
                               //alert(data);
                        }


                    });
    		
    		// Confirm stort as finished for this id
    			
    		$(this).parent().parent().remove();
                location.reload();
                
    	});
    	
    	$('.reject_story_submit').click(function (event) {
    		event.preventDefault();
    		
    		var storyId = $(this).parent().parent().find("input:hidden").val();              
    		
    		// Mark this story as unfinished and put it back to product backlog
                var form = "story_id="+storyId;
            
                var ajaxReq =  $.post("./php/ownerEditStory.php?method=reject",               //URL
                    form,                                  //podatki
                    function(data) {                  //Funkcija ob uspehu

                        var obj = $.parseJSON(data);

                        //alert("msg_data: "+obj.msg);
                        //$("#error_msg_sprint").html(obj.msg);
                        //alert(data);
                        if(obj.success == 1){   //Ob uspe��nem sporo��ilu
                           //resetForm($('#add_sprint_form')); //Pobrisemo formo, ce je vse ok
                               //alert(data);
                        }


                    });
    			
    		$(this).parent().parent().remove();
                location.reload();
    	});
    	
    	// =========================================================
    	// Work time
    	// =========================================================
    	
    	$(".show_work_time").click(function (event) {
    		event.preventDefault();
    		$(this).attr('id', 'trigger_id');
    		
    		var task_id = $(this).parent().parent().find("input:hidden").val();
    		var usr_id = $(this).parent().parent().find("input:hidden").next().val();
    		
    		// $('#username').html(task_id + " " + usr_id);
    		// Zgradi tabelo v dialogu za case za ta task id
    		var ajaxUrl = "php/editWorkTask.php";
    		var ajaxData = "task_id="+task_id+"&usr_id="+usr_id;
    		var popUp = $(this);
    		
    		var ajaxRequest = $.get(ajaxUrl, ajaxData, function(data){
    			var obj = $.parseJSON(data)
    			//alert(obj.task_id + " " + obj.usr_id);
    			$("#task_work").html(obj.result);
    		
    		
    		});
    		
                   
            $("#task_work").dialog("open");

    		
    	});
    	
    	$( "#task_work" ).dialog({
    		autoOpen: false,
    		open: function(event, ui) {
    			$("input").blur();
    		},
    	    height: 800,
    	    width: 650,
    	    modal: true,
    	    buttons: {
    	    	"Save": function() {
    	    	// http://stackoverflow.com/questions/2075658/looping-through-html-table-with-jquery
    	    	    	
    	    	    var array = Array();	
    	    		$("#tasktable tbody tr").each(function(i, v){
    	    			array[i] =  Array();			
    	    			$(this).find('td').each(function(ii, vv){
    	    				
    	    				var value = ( $(":first-child", this).is(":input") ) 
   								? $(":first-child", this).val() 
    							: ( $(this).text() != "" ) 
      							? $(this).text() 
      							: $(this).html() ;
      							
      							array[i][ii] = value;
  								
    	    			});	    			    	    			
    	    		});
	         	
    	         	//$('#username').html(date_id);
    	         	
    	         	var ajaxUrl = "php/editWorkTask2.php";
    	         		
    	         	var ajaxRequest = $.post(ajaxUrl, {'array[]': array}, function(data){ 
    	         		var obj = $.parseJSON(data);
                                if(obj.fail!=null)
                                    alert(obj.fail);
                                else location.reload();
    	         		
    	         	});
    	            $(this).dialog("close");
    	        }
    	    },
    	    close: function() {
    	    	$("#trigger_id").attr('id', '');
    	        allFields.val("");
    	        $("#task_work").html("");
    	    }
    	});
    	
    	// =========================================================
    	// Project wall
    	// =========================================================
    	
    	$(".delete_post").click(function (event) {
    		event.preventDefault();
    		$(this).attr('id', 'trigger_id');
    		$("#delete_post_dialog").dialog("open");
                
    	});
        	
    	$("#delete_post_dialog").dialog({
    		autoOpen: false,
    	    height: 200,
    	    width: 650,
    	    modal: true,
    	    buttons: {
    	    	"Delete": function() {
                        var trigger = $("#trigger_id"); //Zapomnimo si ga zaradi funkcije v AJAX klicu
    	         	var post_id = trigger.parent().parent().parent().find("input:hidden").val();
                        
                        $.get("./php/postToWall.php?delete_post_id="+post_id, function(data){
                            //Ob uspešnem AJAX klicu izbrisemo post
                            trigger.parent().parent().parent().slideUp();
                        });
    	         	
    	         	
    	         	
    	            $(this).dialog("close");
    	        },
    	        Cancel: function() {
    	          	$(this).dialog("close");
    	        }
    	    },
    	    close: function() {
    	    	$("#trigger_id").attr('id', '');
    	        allFields.val("");
    	    }
    	});
        
        $(".delete_comment").click(function (event) {
    		event.preventDefault();
    		$(this).attr('id', 'del_id');
    		$("#delete_comment_dialog").dialog("open");
    	});
        
        $("#delete_comment_dialog").dialog({
    		autoOpen: false,
    	    height: 200,
    	    width: 650,
    	    modal: true,
    	    buttons: {
    	    	"Delete": function() {
                        var trigger = $("#del_id");
    	         	var comment_id = trigger.parent().parent().find("input:hidden").val();
                        var form = "delete_comment_id="+comment_id;
                        
                        $.post("./php/addCommentary.php?delete_comm=yes", 
                        form,
                        function(data){
                            //alert("msg_data: "+form);
                            //Ob uspešnem AJAX klicu izbrisemo post
                            var rmv = trigger.parent().parent();
                            var nxt = rmv.next();
                            var nxtbr = nxt.next();
                            rmv.remove();
                            nxt.remove();
                            nxtbr.remove();
                        });
    	         	
    	         	
    	         	
    	            $(this).dialog("close");
    	        },
    	        Cancel: function() {
    	          	$(this).dialog("close");
    	        }
    	    },
    	    close: function() {
    	    	$("#del_id").attr('id', '');
    	        //allFields.val("");
    	    }
    	});
        
        /*
        $("#import").click(function (event) {
            event.preventDefault(); 
                
            $(this).attr('id', 'trigger_button');
            //Podatki iz forme
            var content = $('#documentation_textarea').val();
            var form = $('#doc_form').serialize();
            var fajl = $('#file').val();
            form = form+"&file="+fajl+"&method=import";

            //alert(content);
            //alert(form);
            //alert(fajl);

            //AJAX request using jquery
            var ajaxReq = $.post("./php/editDocumentation.php",      //URL
                form,                                       //podatki
                function(data) {                            //Funkcija ob uspehu
                    //alert(form);
                    var response = $.parseJSON(data);
                    
                    if (response.success < 1)
                        alert("Wrong file format or file doesen't exist!");
                    else
                        $('#documentation_textarea').val(content + response.content);
                });
	});   */  
        
        $("#export").click(function (event) {
            event.preventDefault(); 
                
            $(this).attr('id', 'trigger_button');
            var form = $('#doc_form').serialize();
            
            /*
            var alphaExp = /^\s*[a-zA-Z0-9_,\s-]+\s*$/;
             
            var file = prompt("Enter file name: ");
            if (file == null || file == ""){
                //alert("Name not entered.");
                //window.location = "http://localhost/TpoProject/project_wall.php?tab=2";
                return;
            }
            else if (!file.match(alphaExp)){
                alert("Name must contain letters only.")
                //window.location = "http://localhost/TpoProject/project_wall.php?tab=2";
                return;
            }*/
            form = form+"&file="+file+"&method_export=export";

            //AJAX request using jquery
            var ajaxReq = $.post("./php/editDocumentation.php",      //URL
                form,                                       //podatki
                function(data) {                            //Funkcija ob uspehu
                    //alert(form);
                    var response = $.parseJSON(data);
                    
                    if (response.success < 1){
                        alert("File already exists!");
                    }
                    else{
                        $('#download').css('visibility','visible');
                        //$('#download').attr('href',"http://localhost/TpoProject/php/"+file+".txt");
                        //$('#download').attr('download',file+".txt");
                        $("#export_dialog").dialog("open");
                    }
                           
                });
	});
        
        $("#export_dialog").dialog({
            autoOpen: false,
    	    height: 250,
    	    width: 650,
    	    modal: true,
    	    buttons: {
    	    	"Ok": function() {
                              	
    	            $(this).dialog("close");
    	        }
    	        
    	    },
    	    close: function() {
    	    	//$("#del_id").attr('id', '');
    	        //allFields.val("");
    	    }
    	});
        
        
        
        
       $("#import").click( function (event) {

            var fajl = $('#file').val();        
            
            if (fajl == null || fajl == ""){
                alert("No file chosen");
                event.preventDefault();
            }
           
        });
        //On focus in we enable checkboxes if scrum master or owner
        $("select[name=master]").focusin(function(event){
            var master_scrum_id=$(this).parent().parent().find("select[name=master]").val();
            //var owner_scrum_id=$(this).parent().parent().find("select[name=leader]").val();
            $(this).parent().parent().find("input:checkbox[value="+master_scrum_id+"]").attr("checked",false).attr("disabled",false);
            //$("input:checkbox[value="+owner_scrum_id+"]").attr("checked",false).attr("disabled",false);
            
        });
        //On focus out disable them and check if scrum master or owner
        $("select[name=master]").focusout(function(event){
            var master_scrum_id=$(this).parent().parent().find("select[name=master]").val();
            //var owner_scrum_id=$(this).parent().parent().find("select[name=leader]").val();
            $(this).parent().parent().find("input:checkbox[value="+master_scrum_id+"]").prop("disabled",true);//.prop("checked",true)
            //$("input:checkbox[value="+owner_scrum_id+"]").attr("checked",true).attr("disabled",true);
        });
        function gup(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);
            if (results == null)
                return "";
            else
            return results[1];
        }   
        function reloadWithoutParam(){
            window.location = window.location.href.split("?")[0];
        }
});

